import { TabItem } from "@/_gx/Types";

/**
 * _Layout.vue和_Tab.vue中，针对已打开页面的选项卡数据的处理
 */
export const tabStore = defineStore({
    id: "tabs",
    state: () => ({
        list: Gx.GetSession(Config._TAB_KEY) as Array<TabItem>,
    }),

    actions: {
        //得到list
        GetList(): Array<TabItem> {
            return Gx.IsEmpty(this.list) ? [] : this.list;
        },

        //得到只有name的list
        GetNameList(): Array<any> {
            return Gx.IsEmpty(this.list) ? [] : this.list.map((x) => x.name);
        },

        //添加
        Add(data: TabItem): void {
            if (Gx.IsEmpty(this.list)) {
                this.list = [];
            }

            this.list.unshift(data);
            Gx.SetSession(Config._TAB_KEY, this.list);
        },

        //关闭(删除)
        Close(index: number): void {
            this.list.splice(index, 1);
            Gx.SetSession(Config._TAB_KEY, this.list);
        },

        //关闭所有
        CloseAll(): void {
            this.list = [];
            Gx.SetSession(Config._TAB_KEY, this.list);
        },

        //关闭其它
        CloseOther(data: Array<TabItem>): void {
            this.list = data;
            Gx.SetSession(Config._TAB_KEY, this.list);
        },

        //设置激活
        SetActive(index: number): void {
            if (Gx.IsEmpty(this.list)) {
                return;
            }

            this.list.forEach((x) => {
                x.isActive = false;
            });

            if (index > -1) {
                this.list[index].isActive = true;
            }

            Gx.SetSession(Config._TAB_KEY, this.list);
        },

        //根据索引得到当前标签项
        GetByIndex(idx: number): TabItem {
            if (idx == -1) {
                return null;
            }

            return this.list[idx];
        },

        //根据传入的索引，得到后一个标签信息
        GetNextItem(curIdx: number): TabItem {
            if (curIdx + 1 > this.list.length - 1) {
                return this.list[this.list.length - 1];
            }

            return this.list[curIdx + 1];
        },

        //根据传入的索引，得到前一个标签信息
        GetPrevItem(curIdx: number): TabItem {
            if (curIdx - 1 < 0) {
                return null;
            }

            return this.list[curIdx - 1];
        },

        //得到当前激活的标签索引
        GetActiveIndex(): number {
            let idx = this.list.findIndex((x: TabItem) => {
                return x.isActive;
            });

            return idx;
        },

        //交换2个元素
        Swap(idx1: number, idx2: number): void {
            let item1 = this.list[idx1];

            this.list[idx1] = this.list[idx2];
            this.list[idx2] = item1;

            Gx.SetSession(Config._TAB_KEY, this.list);
        },
    },
});
